using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Transactions;
using System.Web.Mvc;
using System.Xml.Serialization;
using eSeller.Models;
using Orchard.Themes;
using System.Linq;

namespace eSeller.Controllers
{
    [Themed]
    public class SellerMainController : Controller, IController
    {
        public SellerMainController()
        {
        }
        EsellerModelEntities _esellerRepo;

        private EsellerModelEntities EsellerRepo
        {
            get
            {
                if (_esellerRepo == null)
                {

                    var modevaConStr = ConfigurationManager.ConnectionStrings["EsellerModelEntities"].ConnectionString.Replace("|ModuleDir|", ModuleDir);
                    _esellerRepo = new EsellerModelEntities(modevaConStr);
                }
                return _esellerRepo;
            }
        }
        public ActionResult Index()
        {
            using (new TransactionScope(TransactionScopeOption.Suppress))
            {
                foreach (var product in EsellerRepo.Products)
                {
                    product.CalculateVoteScore();
                    if (product.UiData != null)
                        product.UiData.ToString();
                }

                foreach (var productCategory in EsellerRepo.ProductCategories)
                {
                    if (productCategory.UiData != null)
                        productCategory.UiData.ToString();
                }

                return View("eSellerMainView", new EsellerViewModel
                {
                    Id = 9,
                    Products = EsellerRepo.Products.ToList(),
                    ProductCategories = EsellerRepo.ProductCategories.ToList()
                });
            }
        }

        public ActionResult AddProduct()
        {
            return PartialView("ProductItem", new Product {Name = "Hero"});
        }

        private void SyncUiData(UiData target, UiData source)
        {
            target.X = source.X;
            target.Y = source.Y;
            target.Width = source.Width;
            target.Height = source.Height;
        }

        public void SavePosition(EsellerViewModel input)
        {
            using (new TransactionScope(TransactionScopeOption.Suppress))
            {
                foreach (var item in input.Products)
                {
                    var product = EsellerRepo.Products.Single(p => p.Id == item.Id);
                    if (product.UiData == null)
                        product.UiData = new UiData();
                    SyncUiData(product.UiData, item.UiData);
                }

                foreach (var item in input.ProductCategories)
                {
                    var cat = EsellerRepo.ProductCategories.Single(p => p.Id == item.Id);
                    if (cat.UiData == null)
                        cat.UiData = new UiData();
                    SyncUiData(cat.UiData, item.UiData);
                }

                EsellerRepo.SaveChanges();
            }
        }

        public void DeleteProduct(int id)
        {
            using (new TransactionScope(TransactionScopeOption.Suppress))
            {
                var toDel = new List<object>();
                var product = EsellerRepo.Products.Single(p => p.Id == id);
                foreach (var v in product.Votes)
                {
                    toDel.Add(v);
                }

                toDel.Add(product);
                foreach (var item in toDel)
                {
                    EsellerRepo.DeleteObject(item);
                }

                EsellerRepo.SaveChanges();
            }

        }

        public JsonResult GetJson()
        {
            using (new TransactionScope(TransactionScopeOption.Suppress))
            {
                foreach (var product in EsellerRepo.Products)
                {
                    product.CalculateVoteScore();
                }

                return Json(new EsellerViewModel { Id = 9, Products = EsellerRepo.Products.ToList() }, JsonRequestBehavior.AllowGet);
            }
        }

        const string SampleText = "Les invités de la semaine Dominique de Villepin (République Solidaire), Clémentine Autain (Front de Gauche, porte-parole du candidat Jean-Luc Mélenchon) et Sergio Coronado (Europe Ecologie les Verts, porte-parole de la candidate Eva Joly) se sont succédés sur le plateau de France 2012. Ils ont répondu aux questions de Philippe Dessaint et des intervenants de l'émission portant sur leurs programmes internationaux respectifs.";

        static string UppercaseFirst(string s)
        {
            // Check for empty string.
            if (string.IsNullOrEmpty(s))
            {
                return string.Empty;
            }
            // Return char and concat substring.
            return char.ToUpper(s[0]) + s.Substring(1);
        }

        public void GenerateSample()
        {
            var random = new Random();
            var words = SampleText.Split(' ');


            using (new TransactionScope(TransactionScopeOption.Suppress))
            {
                var toDel = new List<object>();
                foreach (var product in EsellerRepo.Products)
                {
                    toDel.AddRange(product.Votes);
                    toDel.Add(product);
                }
                foreach (var o in toDel)
                {
                    EsellerRepo.DeleteObject(o);
                }

                EsellerRepo.SaveChanges();

                var pcs = EsellerRepo.ProductCategories.ToList();

                for (int i = 0; i < 40; i++)
                {
                    var txt = UppercaseFirst(words[random.Next(words.Length - 1)]) + " " + UppercaseFirst(words[random.Next(words.Length - 1)]);
                    var p = new Product { Name = txt, ProductCategory = pcs[random.Next(pcs.Count)] };
                    EsellerRepo.AddToProducts(p);
                    for (int j = 0; j < random.Next(100); j++)
                    {
                        p.Votes.Add(new Vote { Score = random.Next(5), VoteDate = DateTime.Now });
                    }

                }

                EsellerRepo.SaveChanges();
            }
        }

        private readonly string[] _bColors = new[] { "#613DBC", "#2779EC", "#00A21B", "#BC1E49", "black", "#9D6710" };

        public string RateProduct(string id, int rating)
        {
            var pId = int.Parse(id.Replace("rate_", ""));

            using (new TransactionScope(TransactionScopeOption.Suppress))
            {
                var product = EsellerRepo.Products.Single(p => p.Id == pId);
                product.Votes.Add(new Vote { Score = rating, VoteDate = DateTime.Now });
                EsellerRepo.SaveChanges();
                product.CalculateVoteScore();
                return string.Format("{0:0.0}", product.VoteScore);
            }
        }


        public string ModuleDir
        {
            get { return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules", "eSeller"); }
        }

        public string ModuleUrl
        {
            get { return "/Modules/HelloWorld"; }

        }

        public void LogXml(object input)
        {
            var xml = new XmlSerializer(input.GetType());
            var stream = System.IO.File.Create(Path.Combine(ModuleDir, "log.xml"));
            xml.Serialize(stream, input);
            stream.Close();
        }

        public void Log(Exception ex)
        {
            System.IO.File.WriteAllText(@"C:\log.txt", ex.Message + "\r\n" + ex.StackTrace);
        }

        public void Log(string txt)
        {
            System.IO.File.WriteAllText(Path.Combine(ModuleDir, "log.txt"), txt);
        }
    }
}
